package com.taritari.journal.services;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taritari.journal.entity.dto.CommentRoBotDto;
import com.taritari.journal.entity.dto.JournalAddDto;
import com.taritari.journal.entity.dto.SentimentMqDto;
import com.taritari.journal.entity.dto.UserLikeDto;
import com.taritari.journal.entity.po.BrowseLog;
import com.taritari.journal.entity.po.JournalUser;
import com.taritari.journal.entity.po.TreeHole;
import com.taritari.journal.entity.vo.SentimentClassify;
import com.taritari.journal.entity.vo.TreeHoldDetailVo;
import com.taritari.journal.entity.vo.TreeHoldVo;
import com.taritari.journal.mapper.TreeHoleMapper;
import com.taritari.journal.services.impl.TreeHoleServiceImpl;
import com.taritari.journal.utils.DateUtil;
import com.taritari.journal.utils.JwtUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author taritari
 * @date 2024-01-18 16:01
 * @description 树洞
 */
@Service
public class TreeHoleService extends ServiceImpl<TreeHoleMapper, TreeHole> implements TreeHoleServiceImpl {
    @Autowired
    private TreeHoleMapper treeHoleMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CommentService commentService;
    @Autowired
    private SentimentClassifyService sentimentClassifyService;


    /**
     * 树洞~开始漫游功能
     * */
    @Override
    public TreeHoldDetailVo treeRoam(String userId) {
        // 通过id获取用户今日的排除标签
        String tag = stringRedisTemplate.opsForValue().get(userId);
        TreeHole treeHole = treeHoleMapper.randomQueryTreeHole(tag);
        int authorId = treeHole.getAuthorId();
        JournalUser journalUser = userService.queryUserInfoById(authorId);
        TreeHoldDetailVo treeHoldDetailVo = new TreeHoldDetailVo();
        treeHoldDetailVo.setContent(treeHole.getContent());
        treeHoldDetailVo.setTreeHoleId(treeHole.getId());
        treeHoldDetailVo.setTitle(treeHole.getTitle());
        treeHoldDetailVo.setAuthorId(treeHole.getAuthorId());
        treeHoldDetailVo.setCreatTime(dateUtil.dateFormat(treeHole.getCreatedTime()));
        //通过树洞id获取评论数
        int treeHoldId = commentService.getCount(treeHole.getId());
        treeHoldDetailVo.setCommentCount(treeHoldId);
        treeHoldDetailVo.setAuthorName(journalUser.getNickname());
        treeHoldDetailVo.setImgUrl(journalUser.getImgUrl());
        treeHoldDetailVo.setLikeCounts(treeHole.getLikes());
        //浏览表+1
        BrowseLog browseLog = new BrowseLog();
        browseLog.setUserId(Integer.parseInt(userId));
        browseLog.setJournalNumber(treeHole.getNumber());
        browseLog.setBrowseTime(cn.hutool.core.date.DateUtil.date(System.currentTimeMillis()));
        browsedLogMq(browseLog);
        return treeHoldDetailVo;
    }

    /**
     * rabbitmq的生产者
     * @param
     * */
    public void browsedLogMq(BrowseLog browseLog){
        String jsonString = JSON.toJSONString(browseLog);
        // 交换机名
        String exchangeName = "journal_browsLog";
        //路由名，由交换机绑定
        String routingKey = "log";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,jsonString);
    }


    /**
     * 用户是否点赞
     * */
    @Override
    public int userIsLike(int userId, int treeHoleId) {
        int res = treeHoleMapper.queryUserLike(userId, treeHoleId);
        return res;
    }
    /**
     * 用户点击喜欢
     * */
    @Override
    public int userLike(int userId, int treeHoleId) {
        int res = treeHoleMapper.queryUserLike(userId, treeHoleId);
        if (res==1){ //存在-再点一次就不喜欢
            treeHoleMapper.likesChanges(-1,treeHoleId);
            int r = treeHoleMapper.deleteUserLike(userId, treeHoleId);
            return r;
        }else { //不存在-点一次就喜欢
            treeHoleMapper.likesChanges(1,treeHoleId);
            int r = treeHoleMapper.insertUserLike(userId,treeHoleId);
            return r;
        }
    }

    /**
     * 投递树洞
     * */
    @Override
    public int deliverTreeHold(TreeHole treeHole) {
        TreeHoleService treeHoleService = new TreeHoleService();
        // 先判断是否投递过
        LambdaQueryWrapper<TreeHole> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(TreeHole::getNumber,treeHole.getNumber());
        TreeHole isExit = treeHoleMapper.selectOne(lambdaQueryWrapper);
        if (BeanUtil.isNotEmpty(isExit)){
            return 0;
        }else {
            treeHole.setCreatedTime(cn.hutool.core.date.DateUtil.date(System.currentTimeMillis()));

            int res = treeHoleMapper.insert(treeHole);
            System.out.println(treeHole.getTitle());
            if (res==1){
                // 机器人自动评论一次
                SentimentClassify sentimentClassify = sentimentClassifyService.selectOneByJournalNumber(treeHole.getNumber());
                String text = sentimentClassify.getText();
                CommentRoBotDto commentRoBotDto = new CommentRoBotDto();
                commentRoBotDto.setNumber(treeHole.getNumber());
                commentRoBotDto.setText(text);
                commentMq(commentRoBotDto);
            }
            return res;

        }

    }


    /**
     * rabbitmq的生产者
     * @param
     * */
    public void commentMq(CommentRoBotDto commentRoBotDto){
        String jsonString = JSON.toJSONString(commentRoBotDto);
        // 交换机名
        String exchangeName = "journal_comment";
        //路由名，由交换机绑定
        String routingKey = "comment";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,jsonString);
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//
//            @Override
//            public void run() {
//                rabbitTemplate.convertAndSend(exchangeName,routingKey,jsonString);
//                this.cancel();
//
//            }
//        }, 3000);
    }



    /**
     * 获取最新的十篇树洞
     * */
    @Override
    public List<TreeHoldVo> newTreeHold() {
        LambdaQueryWrapper<TreeHole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TreeHole::getIsDelete,0);
        lambdaQueryWrapper.orderByDesc(TreeHole::getCreatedTime);
        lambdaQueryWrapper.last("limit 10");  // 这里的10是您想要的限制数量
        List<TreeHole> treeHoles = treeHoleMapper.selectList(lambdaQueryWrapper);
        List<TreeHoldVo> treeHoldVos = treeHoldFormat(treeHoles);
        return treeHoldVos;
    }

    /**
     * 树洞vo格式format
     * */
    public  List<TreeHoldVo> treeHoldFormat(List<TreeHole> treeHoles){
        List<TreeHoldVo> treeHoldVos = new ArrayList<>();
        for (TreeHole item : treeHoles){
            TreeHoldVo treeHoldVo = new TreeHoldVo();
            JournalUser journalUser = userService.queryUserInfoById(item.getAuthorId());
            treeHoldVo.setTitleUrl(journalUser.getImgUrl());
            treeHoldVo.setTime(dateUtil.dateFormat(item.getCreatedTime()));
            treeHoldVo.setId(item.getId());
            treeHoldVo.setTitle(item.getTitle());
            treeHoldVos.add(treeHoldVo);
        }
        return treeHoldVos;
    }
    /**
     * 获取最多喜欢的十篇
     * */
    @Override
    public List<TreeHoldVo> likeDesc() {
        LambdaQueryWrapper<TreeHole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TreeHole::getIsDelete,0);
        lambdaQueryWrapper.orderByDesc(TreeHole::getLikes);
        lambdaQueryWrapper.last("limit 10");  // 这里的10是您想要的限制数量
        List<TreeHole> treeHoles = treeHoleMapper.selectList(lambdaQueryWrapper);
        List<TreeHoldVo> treeHoldVos = treeHoldFormat(treeHoles);
        return treeHoldVos;
    }
    /**
     * 用户喜欢的树洞
     * */
    @Override
    public List<TreeHoldVo> userLikes(int userId, int page,int pageSize) {
        int offset = (page - 1) * pageSize;
        List<Integer> treeHoldIdList = treeHoleMapper.queryUserLikeTreeHoldId(userId);
        LambdaQueryWrapper<TreeHole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TreeHole::getIsDelete, 0);
        lambdaQueryWrapper.in(TreeHole::getId, treeHoldIdList);
        lambdaQueryWrapper.orderByDesc(TreeHole::getCreatedTime);
        lambdaQueryWrapper.last("limit " + pageSize + " OFFSET " + offset);  // 使用offset和limit替代limit
        List<TreeHole> treeHoles = treeHoleMapper.selectList(lambdaQueryWrapper);
        List<TreeHoldVo> treeHoldVos = treeHoldFormat(treeHoles);
        return treeHoldVos;
    }
    /**
     * 获取用户投递的树洞文章列表
     * */
    @Override
    public List<TreeHoldVo> getUserTreeHolds(int userId,  int page,int pageSize) {
        int offset = (page - 1) * pageSize;
        LambdaQueryWrapper<TreeHole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TreeHole::getIsDelete,0);
        lambdaQueryWrapper.eq(TreeHole::getAuthorId,userId);
        lambdaQueryWrapper.orderByDesc(TreeHole::getCreatedTime);
        lambdaQueryWrapper.last("limit " + pageSize + " OFFSET " + offset);  // 使用offset和limit替代limit
        List<TreeHole> treeHoles = treeHoleMapper.selectList(lambdaQueryWrapper);
        List<TreeHoldVo> treeHoldVos = treeHoldFormat(treeHoles);
        return treeHoldVos;
    }
    /**
     * 通过id获取树洞内容
     * */
    @Override
    public TreeHole getTreeHoldById(int treeHoldId) {
        LambdaQueryWrapper<TreeHole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TreeHole::getId,treeHoldId);
        lambdaQueryWrapper.eq(TreeHole::getIsDelete,0);
        TreeHole treeHole = treeHoleMapper.selectOne(lambdaQueryWrapper);
        return treeHole;
    }

    /**
     * 用户点击树洞卡片返回详情
     * */
    public TreeHoldDetailVo treeHoldCarClick(int treeHoldId){
        TreeHole treeHole = getTreeHoldById(treeHoldId);
        int authorId = treeHole.getAuthorId();
        JournalUser journalUser = userService.queryUserInfoById(authorId);
        TreeHoldDetailVo treeHoldDetailVo = new TreeHoldDetailVo();
        treeHoldDetailVo.setContent(treeHole.getContent());
        treeHoldDetailVo.setTreeHoleId(treeHole.getId());
        treeHoldDetailVo.setTitle(treeHole.getTitle());
        treeHoldDetailVo.setAuthorId(treeHole.getAuthorId());
        treeHoldDetailVo.setCreatTime(dateUtil.dateFormat(treeHole.getCreatedTime()));
        //通过树洞id获取评论数
        int commentCount = commentService.getCount(treeHole.getId());
        treeHoldDetailVo.setCommentCount(commentCount);
        treeHoldDetailVo.setAuthorName(journalUser.getNickname());
        treeHoldDetailVo.setImgUrl(journalUser.getImgUrl());
        treeHoldDetailVo.setLikeCounts(treeHole.getLikes());
        return treeHoldDetailVo;
    }


    /**
     * rabbitmq的生产者
     * @param
     * */
    public void userLikeMq(UserLikeDto userLikeDto){
        String jsonString = JSON.toJSONString(userLikeDto);
        // 交换机名
        String exchangeName = "journal_treeHold";
        //路由名，由交换机绑定
        String routingKey = "like";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,jsonString);
    }

}
